package com.stone.framework.core.util;

import org.springframework.data.jpa.domain.Specification;

public final class JpaSpecifications {

    public static <T> Specification<T> equals(String attribute, Class<?> attributeType, Object field) {
        return isBlank(field) ? null
            : (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get(attribute).as(attributeType), field);
    }

    public static <T> Specification<T> equals(String attribute, String field) {
        return equals(attribute, String.class, field);
    }

    public static <T> Specification<T> contains(String attribute, String field) {
        return isBlank(field) ? null
            : (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get(attribute), "%" + field + "%");
    }

    private static boolean isBlank(Object field) {
        return field == null || "".equals(field);
    }

}
